package com.songlanyun.modules.wechat.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.live.WxMaLiveGoodInfo;
import cn.binarywang.wx.miniapp.bean.live.WxMaLiveResult;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;
import com.songlanyun.modules.wechat.config.WxMaConfiguration;
import com.songlanyun.modules.wechat.dao.WechatLiveGoodsDao;
import com.songlanyun.modules.wechat.entity.WechatLiveGoods;
import com.songlanyun.modules.wechat.service.WechatLiveGoodsService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 直播商品管理
 */
@Service("echatLiveGoodsService")
@Slf4j
public class WechatLiveGoodsServiceImpl extends ServiceImpl<WechatLiveGoodsDao, WechatLiveGoods> implements WechatLiveGoodsService {

    @Value("${wx.miniapp.configs[0].appid}")
    private String appid;

    @Value("${wx.miniapp.configs[0].upload}")
    private String uploadDirStr;


    @Override
    public WechatLiveGoods create(WechatLiveGoods entity) {
        WxMaService wxMaService = WxMaConfiguration.getMaService(appid);
        try {
            WxMaLiveGoodInfo goods = new WxMaLiveGoodInfo();
            BeanUtils.copyProperties(entity, goods);
            goods.setPrice(new BigDecimal(entity.getPrice()));
            if (StringUtils.isNotBlank(entity.getPrice2())) {
                goods.setPrice2(new BigDecimal(entity.getPrice2()));
            }
            goods.setPriceType(Integer.parseInt(entity.getPriceType()));
            goods.setCoverImgUrl(uploadPhotoToWx(wxMaService, entity.getCoverImgeUrl()));
            WxMaLiveResult wxMaLiveResult = wxMaService.getLiveGoodsService().addGoods(goods);
            entity.setGoodsId(Long.valueOf(wxMaLiveResult.getGoodsId()));
            entity.setAuditId(Long.valueOf(wxMaLiveResult.getAuditId()));
            this.baseMapper.insert(entity);
        } catch (WxErrorException e) {
            String error = e.toString();
            if (error.indexOf("300002") != -1) {
                throw new RuntimeException("商品名称，最长14个汉字，1个汉字相当于2个字符");
            } else if (error.indexOf("300003") != -1) {
                throw new RuntimeException("价格输入不合规（如现价比原价大、传入价格非数字等）");
            } else if (error.indexOf("300004") != -1) {
                throw new RuntimeException("商品名称存在违规违法内容");
            } else if (error.indexOf("300006") != -1) {
                throw new RuntimeException("图片上传失败（如：mediaID过期）");
            } else if (error.indexOf("300007") != -1) {
                throw new RuntimeException("线上小程序版本不存在该链接");
            } else if (error.indexOf("300021") != -1) {
                throw new RuntimeException("商品添加成功，审核失败");
            } else if (error.indexOf("300018") != -1) {
                throw new RuntimeException("商品图片尺寸过大");
            } else {
                throw new RuntimeException("微信调用失败！" + e.toString());
            }
        }
        return entity;
    }


    @Override
    public WechatLiveGoods modify(WechatLiveGoods entity) {
        WxMaService wxMaService = WxMaConfiguration.getMaService(appid);
        try {
            WxMaLiveGoodInfo goods = new WxMaLiveGoodInfo();
            BeanUtils.copyProperties(entity, goods);
            goods.setGoodsId(entity.getGoodsId().intValue());
            goods.setCoverImgUrl(uploadPhotoToWx(wxMaService, entity.getCoverImgeUrl()));
            goods.setPrice(new BigDecimal(entity.getPrice()));
            goods.setPriceType(Integer.parseInt(entity.getPriceType()));
            if (StringUtils.isNotBlank(entity.getPrice2())) {
                goods.setPrice2(new BigDecimal(entity.getPrice2()));
            }
            boolean res = wxMaService.getLiveGoodsService().updateGoods(goods);
            if (res) {
                entity.setAuditStatus(0);
                this.baseMapper.updateById(entity);
            } else {
                throw new RuntimeException("修改直播商品错误");
            }
        } catch (WxErrorException e) {
            String error = e.toString();
            if (error.indexOf("300002") != -1) {
                throw new RuntimeException("商品名称，最长14个汉字，1个汉字相当于2个字符");
            } else if (error.indexOf("300003") != -1) {
                throw new RuntimeException("价格输入不合规（如现价比原价大、传入价格非数字等）");
            } else if (error.indexOf("300004") != -1) {
                throw new RuntimeException("商品名称存在违规违法内容");
            } else if (error.indexOf("300006") != -1) {
                throw new RuntimeException("图片上传失败（如：mediaID过期）");
            } else if (error.indexOf("300007") != -1) {
                throw new RuntimeException("线上小程序版本不存在该链接");
            } else if (error.indexOf("300021") != -1) {
                throw new RuntimeException("商品添加成功，审核失败");
            } else if (error.indexOf("300018") != -1) {
                throw new RuntimeException("商品图片尺寸过大");
            } else if (error.indexOf("300010") != -1) {
                throw new RuntimeException("商品审核中不允许修改");
            } else {
                throw new RuntimeException("微信调用失败！" + e.toString());
            }
        }
        return this.getById(entity.getGoodsId());
    }


    @Override
    public void remove(Long id) {
        WxMaService wxMaService = WxMaConfiguration.getMaService(appid);
        try {
            wxMaService.getLiveGoodsService().deleteGoods(id.intValue());
            this.removeById(id);
        } catch (WxErrorException e) {
            String error = e.toString();
            if (error.indexOf("300015") != -1) {
                throw new RuntimeException("小程序中不存在此商品");
            } else if (error.indexOf("300014") != -1) {
                throw new RuntimeException("正在审核的商品不能删除");
            } else {
                throw new RuntimeException("微信调用失败！" + e.toString());
            }
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String name = MapUtil.getStr(params, "name");
        Integer auditStatus = MapUtil.getInt(params, "auditStatus");
        IPage<WechatLiveGoods> page = this.page(
                new Query<WechatLiveGoods>().getPage(params),
                new LambdaQueryWrapper<WechatLiveGoods>()
                        .like(StringUtils.isNotBlank(name), WechatLiveGoods::getName, name)
                        .eq(auditStatus != null, WechatLiveGoods::getAuditStatus, auditStatus)

        );
        return new PageUtils(page);
    }


    /**
     * 同步商品更新审核状态
     *
     * @return
     */
    @Override
    public boolean synchroWxOlLive(List<Integer> goodsIds) {
        try {
            WxMaService wxMaService = WxMaConfiguration.getMaService(appid);
            WxMaLiveResult liveInfos = wxMaService.getLiveGoodsService().getGoodsWareHouse(goodsIds);
            if (liveInfos != null && liveInfos.getGoods() != null && liveInfos.getGoods().size() > 0) {
                WechatLiveGoods wechatLiveGoods;
                for (WxMaLiveResult.Goods wxGoods : liveInfos.getGoods()) {
                    wechatLiveGoods = this.baseMapper.selectById(wxGoods.getGoodsId());
                    if (wechatLiveGoods == null) {
                        continue;
                    }
                    wechatLiveGoods.setAuditStatus(wxGoods.getAuditStatus());
                    this.baseMapper.updateById(wechatLiveGoods);
                }
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 上传临时素材
     *
     * @param wxMaService WxMaService
     * @param picPath     图片路径
     * @return WxMpMaterialUploadResult
     * @throws WxErrorException
     */
    private String uploadPhotoToWx(WxMaService wxMaService, String picPath) throws WxErrorException {
        if (StringUtils.isNotBlank(picPath)) {
            String filename = (int) System.currentTimeMillis() + ".png";
            String downloadPath = uploadDirStr + filename;
            long size = HttpUtil.downloadFile(picPath, cn.hutool.core.io.FileUtil.file(downloadPath));
            picPath = downloadPath;
            File picFile = new File(picPath);
            log.info("picFile name : {}", picFile.getName());
            WxMediaUploadResult wxMediaUploadResult = wxMaService.getMediaService().uploadMedia(WxConsts.MediaFileType.IMAGE, picFile);
            log.info("wxMpMaterialUploadResult : {}", JSONUtil.toJsonStr(wxMediaUploadResult));
            if (wxMediaUploadResult != null) {
                return wxMediaUploadResult.getMediaId();
            }
        }
        return "";
    }


}
